package com.zuoyy.admin.system.controller;

import com.zuoyy.admin.common.BaseController;
import com.zuoyy.admin.common.component.actionLog.action.StatusAction;
import com.zuoyy.admin.common.component.actionLog.annotation.ActionLog;
import com.zuoyy.admin.common.component.actionLog.annotation.EntityParam;
import com.zuoyy.admin.system.service.DeptInterface;
import com.zuoyy.common.enums.ResultEnum;
import com.zuoyy.common.enums.StatusEnum;
import com.zuoyy.common.exception.ResultException;
import com.zuoyy.common.utils.EntityBeanUtil;
import com.zuoyy.common.utils.StatusUtil;
import com.zuoyy.common.utils.TreeUtil;
import com.zuoyy.common.vo.JsonResponse;
import com.zuoyy.modules.common.enums.MenuTypeEnum;
import com.zuoyy.modules.system.domain.Dept;
import com.zuoyy.modules.system.domain.Menu;
import com.zuoyy.modules.system.query.DeptQuery;
import com.zuoyy.modules.system.query.MenuQuery;
import com.zuoyy.modules.system.service.DeptService;
import com.zuoyy.modules.system.service.MenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author 
 */
@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    //页面地址
    private static final String PAGE_PATH = "/system/dept";
    //权限标示
    //private static final String PERMISSION_FLAG = "system:dept:";


    @Autowired
    private DeptInterface deptInterface;
    @Autowired
    private DeptService deptService;


    @GetMapping("/index.shtml")
    //@RequiresPermissions(PERMISSION_FLAG+"index")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("res", getMyResources(request,response));
        return PAGE_PATH+"/index";
    }

    @GetMapping("/list/page")
    //@RequiresPermissions(PERMISSION_FLAG+"list")
    public String listPage(Model model) {
        //model.addAttribute("button", getPageButton(PERMISSION_FLAG+"list"));
        return PAGE_PATH+"/list";
    }

    @GetMapping("/add/page")
    //@RequiresPermissions(PERMISSION_FLAG+"add")
    public String toAdd(Model model,String id) {
        String pid = id;
        model.addAttribute("pid",pid);
        DeptQuery query = new DeptQuery();
        model.addAttribute("pids",deptService.getByQuery(query));
        return PAGE_PATH+"/add";
    }

    @GetMapping("/edit/page/{id}")
    //@RequiresPermissions(PERMISSION_FLAG+"edit")
    public String toEdit(@PathVariable("id") Dept domain, Model model) {
        String pid = domain.getPid();
        model.addAttribute("pid",pid);
        DeptQuery query = new DeptQuery();
        model.addAttribute("pids",deptService.getByQuery(query));
        model.addAttribute("domain", domain);
        return PAGE_PATH+"/add";
    }


    @ResponseBody
    @GetMapping("/list/tree")
    //@RequiresPermissions(PERMISSION_FLAG+"index")
    public JsonResponse tree(){
        DeptQuery query = new DeptQuery();
        Sort sort = new Sort(Sort.Direction.DESC,"sort");
        List<Dept> depts = deptService.getByQuery(query,sort);
        try {
            depts = TreeUtil.getTree(depts,"id");
            return JsonResponse.success(depts);
        } catch (Exception e) {
            throw new ResultException(ResultEnum.ERROR);
        }

    }
    @ResponseBody
    @GetMapping("/list/tree/user")
    //@RequiresPermissions(PERMISSION_FLAG+"index")
    public Object usertree(){
        DeptQuery query = new DeptQuery();
        Sort sort = new Sort(Sort.Direction.DESC,"sort");
        List<Dept> depts = deptService.getByQuery(query,sort);
        try {
            depts = TreeUtil.getTree(depts,"id");
            return buildTree(depts,"0");
        } catch (Exception e) {
            throw new ResultException(ResultEnum.ERROR);
        }

    }

    private Object buildTree(List<Dept> list,String id) {
        List<HashMap<String, Object>> result=new ArrayList<>();
        for (Dept dept : list) {
            HashMap<String, Object> node=new HashMap<>();
            node.put("id", dept.getId());    //节点id
            node.put("name",dept.getDeptName());    //节点数据名称
            node.put("open", false);        //是否展开
            node.put("checked", false);    //是否选中，前台也可以设置是否选中
            if(dept.getChildren().size() != 0) {    //如果下级节点不为空，
                node.put("children",buildTree(dept.getChildren(), id));    //递归加载下级节点
            }
            result.add(node);
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public JsonResponse getListPage(DeptQuery query) {
        return deptInterface.getListPage(query);
    }

    @ResponseBody
    @PostMapping("/save")
    //@RequiresPermissions({PERMISSION_FLAG+"add", PERMISSION_FLAG+"edit"})
    public JsonResponse save(@EntityParam @RequestBody Dept domain) {
        if(domain.getPid().equals("0")){
            domain.setPids("[0]");
        }else{
            // 添加全部上级序号
            Dept d = deptService.findById(domain.getPid());
            domain.setPids(d.getPids() + ",[" + domain.getPid() + "]");
        }
        // 复制保留无需修改的数据
        if (!StringUtils.isEmpty(domain.getId())) {
            Dept b = deptService.findById(domain.getId());
            EntityBeanUtil.copyProperties(b, domain, "pids");
        }
        domain.setSort(Objects.nonNull(domain.getSort())?domain.getSort():0);
        // 保存数据
        deptService.save(domain);
        return JsonResponse.success();
    }

    @ResponseBody
    @RequestMapping("/status/{param}")
    //@RequiresPermissions({PERMISSION_FLAG+"status",PERMISSION_FLAG+"delete"})
    @ActionLog(name = "状态", action = StatusAction.class)
    public JsonResponse status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<String> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        return deptInterface.updateStatus(statusEnum,ids);
    }

}